using System;
using System.Security.Cryptography;
using System.Text;

namespace WebApplication1.Utils
{
    /// <summary>
    /// 密码加密帮助类
    /// </summary>
    public class PasswordHelper
    {
        /// <summary>
        /// 默认加密因子
        /// </summary>
        private static string _defaultSalt = "WebApplication1_Salt";

        /// <summary>
        /// 设置默认加密因子
        /// </summary>
        /// <param name="salt">加密因子</param>
        public static void SetDefaultSalt(string salt)
        {
            if (string.IsNullOrEmpty(salt))
            {
                throw new ArgumentException("加密因子不能为空");
            }
            _defaultSalt = salt;
        }

        /// <summary>
        /// 使用MD5加密密码
        /// </summary>
        /// <param name="password">原始密码</param>
        /// <param name="salt">加密因子（可选）</param>
        /// <returns>加密后的密码</returns>
        public static string EncryptPassword(string password, string? salt = null)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("密码不能为空");
            }

            salt ??= _defaultSalt;
            var passwordWithSalt = $"{password}{salt}";
            
            using (var md5 = MD5.Create())
            {
                var inputBytes = Encoding.UTF8.GetBytes(passwordWithSalt);
                var hashBytes = md5.ComputeHash(inputBytes);
                var sb = new StringBuilder();
                
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("x2"));
                }
                
                return sb.ToString();
            }
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="password">原始密码</param>
        /// <param name="encryptedPassword">加密后的密码</param>
        /// <param name="salt">加密因子（可选）</param>
        /// <returns>是否匹配</returns>
        public static bool VerifyPassword(string password, string encryptedPassword, string? salt = null)
        {
            if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(encryptedPassword))
            {
                return false;
            }

            var hashedPassword = EncryptPassword(password, salt);
            return hashedPassword.Equals(encryptedPassword, StringComparison.OrdinalIgnoreCase);
        }
    }
}